<template>
  <div v-loading="mainLoading" class="app-container layout-container">
    <el-row>
      <el-col :span="6">
        <div v-loading="loadingLeft" class="layout-left">
          <!-- <div class="btn-right-container" style="margin-right:10px">
            <el-button-group id="btnlist">
              <el-button size="medium" type="primary" @click="treeView">
                查看
              </el-button>
              <template v-if="btnPermission.length">
                <el-button v-for="item in btnLists2" :key="item.funCode" v-permission="[item.funCode, btnPermission]" :type="item.color?item.color:'info'" size="medium" :icon="'el-icon-'+(item.icon?item.icon:'setting')" @click="handle('left', item.color ? item.funCode : '')">
                  {{ item.funName }}
                </el-button>
              </template>
            </el-button-group>
          </div> -->
          <div class="btn-right-container" style="margin-right:10px">
            <h2 class="treeTitle">
              父级部门
            </h2>
            <el-button size="medium" type="primary" @click="treeView">
              查看
            </el-button>
          </div>
          <el-tree
            ref="treeForm"
            :data="treeData"
            :props="defaultProps"
            :expand-on-click-node="false"
            show-checkbox
            node-key="id"
            check-strictly
            default-expand-all
            highlight-current
            check-on-click-node
            @check-change="handleClick"
          />
        </div>
      </el-col>
      <el-col :span="18">
        <div v-show="isShowRight" class="layout-right">
          <el-form
            ref="search"
            :inline="true"
            :model="searchForm"
          >
            <el-form-item prop="name" label="部门简称">
              <el-input
                v-model="searchForm.name"
                placeholder="请输入部门简称"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="getTableList"
              >
                查询
              </el-button>
              <el-button
                type="primary"
                @click="resetForm('search')"
              >
                重置
              </el-button>
            </el-form-item>
            <div class="btn-right-container">
              <el-button-group id="btnlist">
                <template v-if="btnPermission.length">
                  <el-button v-for="item in btnLists" :key="item.funCode" v-permission="[item.funCode, btnPermission]" :type="item.color?item.color:'info'" :icon="'el-icon-'+(item.icon?item.icon:'setting')" size="medium" @click="handle(item.color ? item.funCode : '')">
                    {{ item.funName }}
                  </el-button>
                </template>
                <el-button size="medium" type="primary" @click="exportList">
                  导出
                </el-button>
              </el-button-group>
            </div>
          </el-form>
          <el-table
            ref="singleTable"
            v-loading="tableLoading"
            :data="tableData"
            :border="true"
            highlight-current-row
            style="width: 100%; min-height: 620px;"
            max-height="620px"
            @row-click="handleClickRow"
          >
            <el-table-column label=" " width="55">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.checked" @click.native.stop="handleReturn(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column
              :index="indexMethod"
              type="index"
              label="序号"
              align="center"
              width="80"
            />
            <el-table-column
              prop="name"
              label="部门简称"
              align="center"
            />
            <el-table-column
              prop="cname"
              label="部门全称"
              align="center"
            />
            <el-table-column
              prop="deptpath"
              label="部门地址"
              align="center"
            />
            <el-table-column
              prop="coordinate"
              label="部门坐标"
              align="center"
            />
            <el-table-column
              prop="depttel"
              label="部门电话"
              align="center"
            />
            <el-table-column
              label="操作"
              align="center"
              width="120"
            >
              <template slot-scope="scope">
                <el-button type="text" @click="viewDetail(scope.row)">
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="_pagination-t15">
            <!-- <el-pagination
              :page-size="pageSize"
              :current-page.sync="currentPage"
              :total="total"
              background
              layout="total, prev, pager, next"
              @prev-click="currentPage--"
              @next-click="currentPage++"
              @current-change="getTableList"
            /> -->
            <span class="total"> 共 {{ total }} 条数据</span>
          </div>
        </div>
        <div v-show="!isShowRight" class="no-select-info">
          <p>请选择左侧相应的部门进行操作！</p>
        </div>
      </el-col>
    </el-row>
    <el-dialog
      :title="viewTitle"
      :visible.sync="viewDialog"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="view"
        :model="viewForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="name" label="部门简称">
              <el-input
                v-model="viewForm.name"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="cname" label="部门全称">
              <el-input
                v-model="viewForm.cname"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="deptpath" label="部门地址">
          <el-input
            v-model="viewForm.deptpath"
            readonly
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="coordinate" label="部门坐标">
              <el-input
                v-model="viewForm.coordinate"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="depttel" label="部门电话">
              <el-input
                v-model="viewForm.depttel"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <el-dialog
      :title="handleTitle"
      :visible.sync="handleDialog"
      width="40%"
      :close-on-click-modal="false"
    >
      <handle
        v-if="handleDialog"
        :action="action"
        :form-data="handleForm"
        :pid="parentId"
        @closeDialog="closeHandleDialog"
      />
    </el-dialog>
  </div>
</template>

<script>
import mixins, { commonMixin } from '@/utils/mixins'
import handle from './handle'
import * as getApi from '@/api/dept'
import { deepCopy } from '@/utils/common'
function validSelect(data, msg) {
  if (!data) {
    this.$message({
      message: msg,
      type: 'warning'
    })
  }
  return !!data
}
export default {
  components: {
    handle
  },
  mixins: [mixins, commonMixin],
  data() {
    return {
      btnLists: [
        {
          funCode: 'add',
          color: 'primary',
          icon: 'plus',
          funName: '新增部门'
        },
        {
          funCode: 'edit',
          color: 'danger',
          icon: 'edit',
          funName: '修改部门'
        },
        {
          funCode: 'del',
          color: 'warning',
          icon: 'delete',
          funName: '删除部门'
        }
      ],
      searchForm: { // 搜索表单
        name: ''
        // deptpath: ''
      },
      mainLoading: false,
      tableLoading: false,
      tableData: [],
      pageSize: 10,
      currentPage: 1,
      total: 0,
      defaultProps: { // tree属性配置
        children: 'children',
        label: 'name'
      },
      treeData: [], // 左侧树数据
      isShowRight: false, // 右侧列表是否显示
      treeSelected: '', // 左侧tree选中
      i: 0,
      treeHandleForm: {}, // 左侧tree新增修改表单
      loadingLeft: false,
      // btnLists2: [
      //   {
      //     funCode: 'edit',
      //     color: 'danger',
      //     icon: 'edit',
      //     funName: '修改'
      //   },
      //   {
      //     funCode: 'add',
      //     color: 'primary',
      //     icon: 'plus',
      //     funName: '新增'
      //   },
      //   {
      //     funCode: 'del',
      //     color: 'warning',
      //     icon: 'delete',
      //     funName: '删除'
      //   }
      // ],
      viewForm: {}, // 查看详情表单
      viewDialog: false, // 查看详情弹窗
      viewTitle: '查看详情',
      handleDialog: false,
      handleForm: {},
      handleTitle: '新增部门',
      action: 'add',
      downloadOptions: { // 下载文件参数
        url: '/api/dept/download',
        fileName: '部门数据.xlsx'
      }
    }
  },
  computed: {
    parentId() {
      return this.treeSelected ? this.treeSelected.id : null
    }
  },
  watch: {
    parentId(newVal, oldVal) {
      if (newVal) {
        this.getTableList()
      }
    }
  },
  created() {
    this.getTreeList()
  },
  methods: {
    // 获取左侧树的数据
    getTreeList() {
      this.mainLoading = true
      getApi.queryDeptList({}).then(res => {
        if (res.content) {
          // this.treeData = res.content.filter(i => i.children).map(item => {
          this.treeData = res.content.map(item => {
            const temp = deepCopy(item)
            delete temp.children
            return temp
          })
        }
      }).catch(() => {
        this.$message({
          message: '获取数据失败!',
          type: 'error'
        })
        this.tableData = []
      }).finally(() => {
        this.mainLoading = false
      })
    },
    getTableList() {
      this.tableLoading = true
      const params = {
        pageSize: this.pageSize,
        pageNumber: this.currentPage,
        ...this.searchForm,
        pid: this.parentId
      }
      getApi.queryDeptList(params).then(res => {
        if (res && res.content) {
          this.tableData = res.content
          this.total = this.tableData.length
          this.currentSelect = ''
          return
        }
        throw new Error('暂无数据')
      }).catch((err) => {
        this.$message({
          message: err || '获取表格数据失败!',
          type: 'error'
        })
        this.tableData = []
        this.total = this.tableData.length
      }).finally(() => {
        this.tableLoading = false
      })
    },
    handle(name, code) {
      if (name === 'left') {
        code && this[`${name}${code}`]()
        return
      }
      name && this[name](name)
    },
    add() {
      this.action = 'add'
      this.handleDialog = true
    },
    edit() {
      const valid = validSelect.call(this, this.currentSelect, '请先选择一条要修改的部门')
      if (!valid) return
      this.handleForm = this.currentSelect
      this.action = 'edit'
      this.handleTitle = '修改部门'
      this.handleDialog = true
    },
    del() {
      const valid = validSelect.call(this, this.currentSelect, '请先选择一条要删除的部门')
      if (!valid) return
      this.$confirm('确定要删除吗?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.mainLoading = true
        getApi.delDept([this.currentSelect.id]).then(res => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        }).catch(() => {
          this.$message({
            message: '删除失败',
            type: 'error'
          })
        }).finally(() => {
          this.mainLoading = false
          this.getTableList()
        })
      }).catch(() => {})
    },
    leftadd() {
      console.log('leftadd')
    },
    leftedit() {
      console.log('leftedit')
    },
    leftdel() {
      console.log('leftdel')
    },
    // 查看详情
    viewDetail(row) {
      this.viewForm = row
      this.viewTitle = '查看子级部门详情'
      this.viewDialog = true
    },
    // 表格内某一行被点击时触发
    handleClickRow(row) {
      // console.log(row)
      this.tableData.forEach((item, index) => {
        if (item.id !== row.id) {
          item.checked = false
        }
      })
      if (!row.checked) {
        row.checked = true
        this.$refs.singleTable.setCurrentRow(row)
        this.currentSelect = row
      } else {
        row.checked = false
        this.$refs.singleTable.setCurrentRow()
        this.currentSelect = ''
      }
    },
    // 点击表格中的单选按钮
    handleReturn(row) {
      // console.log('点击表格中的单选按钮', row)
      this.tableData.forEach((item, index) => {
        if (item.id !== row.id) {
          item.checked = false
        }
      })
      if (row.checked) {
        this.$refs.singleTable.setCurrentRow()
        this.currentSelect = ''
      } else {
        this.$refs.singleTable.setCurrentRow(row)
        this.currentSelect = row
      }
    },
    // tree查看详情
    treeView() {
      if (!this.treeSelected) {
        this.$message({
          message: '请先选择一条要查看的部门数据!',
          type: 'warning'
        })
        return
      }
      this.viewForm = this.treeSelected
      this.viewTitle = '查看父级部门详情'
      this.viewDialog = true
    },
    // tree单选
    handleClick(data, checked, node) {
      console.log(data, checked, node)
      this.i++
      if (this.i % 2 === 0) {
        if (checked) {
          this.$refs.treeForm.setCheckedNodes([])
          this.$refs.treeForm.setCheckedNodes([data])
          // 交叉点击节点
        } else {
          this.$refs.treeForm.setCheckedNodes([])
          // 点击已经选中的节点，置空
        }
      }
      this.treeSelected = this.$refs.treeForm.getCheckedNodes()[0]
      this.treeSelected && (this.treeHandleForm.id = this.treeSelected.id)
      this.isShowRight = this.treeSelected ? true : false
      console.log(this.isShowRight)
    },
    // 左侧提交删除操作后 重置被选中
    setSelectedNull() {
      this.treeSelected = ''
      this.treeHandleForm.id = ''
      this.isShowRight = false
      this.$refs.treeForm.setCheckedNodes([])
    },
    // 表格序号编号
    indexMethod(indexs) {
      return (indexs + 1) + this.pageSize * (this.currentPage - 1)
    },
    // 重置搜索表单
    resetForm() {
      this.currentPage = 1
      this.$refs.search.resetFields()
    },
    closeHandleDialog(isRefresh) {
      this.handleDialog = false
      isRefresh && this.getTableList()
    }
  }
}
</script>

<style lang="scss" scoped>
.treeTitle {
  text-align: center;
  color: #666;
}
.total {
  font-size: 16px;
  color: #666;
}
</style>
